import re
import tkinter as tk
from bdb import checkfuncname
from tkinter import messagebox

#创建主窗体
root = tk.Tk()
root.title("登录")
#获取设备宽和高
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 500
window_height = 300
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")
root.config(pady=50)

#创建按钮
# login_btn1 = tk.Button(root,text="登录",width=20)
# login_btn1.grid(row=0, column=0)
# login_btn2 = tk.Button(root,text="登录",width=20)
# login_btn2.grid(row=0, column=1)
# login_btn3 = tk.Button(root,text="登录",width=20)
# login_btn3.grid(row=1, column=0)
# login_btn4 = tk.Button(root,text="登录",width=20)
# login_btn4.grid(row=1, column=1)

tk.Label(root,text="用户名",width=27,anchor="e").grid(row=0, column=0)
username = tk.Entry(root,width=20,validate="focusout",validatecommand=lambda : checkUserName())
username.grid(row=0, column=1)
username.grid(row=0, column=1)
lbl_username = tk.Label(root,text="",width=15,bg="red")
lbl_username.grid(row=0, column=2)

tk.Label(root,text="",width=27,anchor="e").grid(row=1, column=0)

tk.Label(root,text="密码",width=27,anchor="e").grid(row=2, column=0)
pwd = tk.Entry(root,width=20)
pwd.grid(row=2, column=1)
lbl_pwd = tk.Label(root,text="",width=15,bg="red")
lbl_pwd.grid(row=2, column=2)

tk.Label(root,text="",width=27,anchor="e").grid(row=3, column=0)

login_btn = tk.Button(root,text="登录",width=10,command=lambda:login())
login_btn.grid(row=4, column=1)

logout_btn = tk.Button(root,text="退出",width=10,command=lambda:logout())
logout_btn.grid(row=4, column=2)

def login():
    str_name = username.get().strip()
    str_pwd = pwd.get().strip()
    if str_name == "admin" and str_pwd == "123456":
        messagebox.showinfo("提示","登录成功")
    else:
        messagebox.showwarning("提示","用户名或密码错误")
def logout():
    result = messagebox.askokcancel("提示","确定要退出吗")
    if result:
        root.quit()
    else:
        pass
def checkUserName():
    name = username.get().strip()
    # 用户名为空，跳过验证
    if not name:
        return True
    else:
        # 判断用户名格式
        if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', username):
            lbl_username.config(text='用户名格式不正确', fg='white')
            return False  # 验证失败返回False
        else:
            lbl_username.config(text='')
            return True

root.mainloop()

















root.mainloop()